package org.example.springsecurity0317.controller;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.example.springsecurity0317.domain.MyUserDetails;
import org.example.springsecurity0317.domain.ResponseResult;
import org.example.springsecurity0317.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Key;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

@RestController
@RequestMapping("/api")
public class UserController {
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    AuthenticationManager authenticationManager;
        //秘钥>=256BIT
    public static Key key= Keys.hmacShaKeyFor("6666668888888866666688888888666666".getBytes());

    @RequestMapping("/login")
    public ResponseResult<String> login(@RequestBody User user){

        String username=user.getName();
        String password=user.getPassword();
//        System.out.println("username:"+username+",password:"+password);
        UsernamePasswordAuthenticationToken authToken=
                new UsernamePasswordAuthenticationToken(username,password,new ArrayList<>(){});
        Authentication authenticate=null;
        try {
            authenticate = authenticationManager.authenticate(authToken);
        }catch (Exception e){
            e.printStackTrace();

            ResponseResult<String> stringResponseResult=new ResponseResult<>(-1,"用户密码不正确",null);

            return stringResponseResult;
        }

        MyUserDetails principal = (MyUserDetails)authenticate.getPrincipal();
        User user1=principal.getUser();
        redisTemplate.opsForValue().set("login:"+user1.getName(),user1);

        HashMap<String,Object> map=new HashMap<>();
        map.put("username","zs");
        map.put("phone","16688886666");
        JwtBuilder jwtBuilder = Jwts.builder()
                .setClaims(map)//设置载荷（声明）
                .setIssuedAt(new Date())//颁发时间
                .setSubject(username)//设置sub，ID
                .signWith(key);//签名
        String token = jwtBuilder.compact();//生成token
        ResponseResult<String> stringResponseResult=new ResponseResult<>(1,"登录成功",token);
        return stringResponseResult;//jwt,string
    }
    @RequestMapping("/user/{userid}")
    @PreAuthorize("hasAuthority('sys:book:look')")
    public ResponseResult<String> getUserInfo(@PathVariable("userid") String userid){
        //打印
        System.out.println("id"+userid);
        ResponseResult<String> stringResponseResult=new ResponseResult<>(1,"登录成功","name:zs");
        return stringResponseResult;
    }

    @RequestMapping("/logout")
    public String logout(){
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        User principal=(User) authentication.getPrincipal();
        String loginKey="login:"+principal.getName();
        redisTemplate.delete(loginKey);
        return "Ok";
    }
}
